package com.example.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * 请求日志过滤器 - 记录所有请求
 */
public class RequestLoggingFilter extends ZuulFilter {

    private static final Logger logger = LoggerFactory.getLogger(RequestLoggingFilter.class);

    @Override
    public String filterType() {
        return "pre"; // 前置过滤器
    }

    @Override
    public int filterOrder() {
        return 10; // 执行顺序（在认证过滤器之后）
    }

    @Override
    public boolean shouldFilter() {
        return true; // 对所有请求生效
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        // 记录请求基本信息
        logger.info("请求信息: {} {} from {}",
                request.getMethod(),
                request.getRequestURL().toString(),
                request.getRemoteAddr());

        // 调试模式下记录请求头
        if (logger.isDebugEnabled()) {
            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                logger.debug("请求头: {} = {}", headerName, request.getHeader(headerName));
            }
        }

        return null;
    }
}